/* 简介：cothread 是一个轻量级协程调度器，由纯C语言实现，易于移植到各种单片机。
 * 同时，由于该调度器仅仅运行在一个实际线程中，所以它也适用于服务器高并发场景。
 *
 * 版本: 1.0.0   2019/02/25
 *
 * 作者: 覃攀 <qinpan1003@qq.com>
 *
 */

#include "rtos.h"

struct timer_param {
    timer_fun fun;
    void *arg;
    int timeout_ms;
    int interval_ms;
};

static coresult_t timer_help_thread(ccb_t *ccb)
{
    struct timer_param *param = ccb->arg;

    thread_start();

    if (param->timeout_ms <= 0 && param->interval_ms <= 0)
        thread_delete();

    if (param->timeout_ms > 0)
    {
        thread_sleep(param->timeout_ms);
        param->fun(param->arg);
    }

    if (param->interval_ms <= 0)
        thread_delete();

    while (1)
    {
        thread_sleep(param->interval_ms);
        param->fun(param->arg);
    }

    thread_end();
}

timer_t timer_set(int timeout_ms, int interval_ms, timer_fun fun, void *arg)
{
    struct timer_param *param = malloc(sizeof(struct timer_param));
    if (param == NULL)
    {
        LOG_ERR("timer malloc failed %d,%d,%p,%p", 
                timeout_ms, interval_ms, fun, arg);
        return 0;
    }

    param->fun = fun;
    param->arg = arg;
    param->timeout_ms = timeout_ms;
    param->interval_ms = interval_ms;

    return (timer_t)thread_create(timer_help_thread, param, THREAD_PRIO_HIGH);
}

/* 不支持删除定时器 */
int timer_destroy(timer_t timerid)
{
    return 0;
}


